<template>
	<div class="search_view">
		<a-space direction="vertical" fill v-show="isEmpty">
			<template #split>
				<a-divider />
			</template>
			搜索到{{ searchResult.movie.total }}条关于{{ searchValue }}的电影
			<movie-show
				v-for="item in searchResult.movie.data"
				:key="item"
				:movieData="item"
			></movie-show>
			搜索到{{ searchResult.article.total }}条关于{{ searchValue }}的文章
			<div class="news_show_content">
				<news-show
					v-for="item in searchResult.article.data"
					:key="item"
					:item="item"
				></news-show>
			</div>
		</a-space>
		<a-empty v-show="!isEmpty" />
	</div>
</template>

<script setup>
import { useHoemStore } from '../../store/home'
import { searchMovie } from '../../api/index'
const isEmpty = ref(true)
const homeStore = useHoemStore()
const searchValue = toRef(homeStore, 'search')
const searchResult = ref({
	movie: { total: 0 },
	article: { total: 0 }
})
// 只用获取一次 用于第一次的内容显示 后续都由监听事件做出反应
homeStore.searchResults.then(res => {
	searchResult.value = res
})
// 监听pinia中search值的变化
homeStore.$subscribe(() => {
	// 在更新dom后再赋值
	nextTick(() => {
		searchMovie(searchValue.value).then(res => {
			// 当返回的值里面有errors数组时 代表没有对应内容 所以需要返回默认内容
			if (res.errors) {
				searchResult.value = homeStore.update(searchResult, {
					movie: { total: 0 },
					article: { total: 0 }
				})
			} else {
				// 当没有errors数组时 就是正常的数据返回
				searchResult.value = homeStore.update(
					searchResult,
					res.searchData
				)
			}
		})
	})
})

watch(
	() => searchResult,
	() => {
		searchResult.value.movie.total <= 0 &&
		searchResult.value.article.total <= 0
			? (isEmpty.value = false)
			: (isEmpty.value = true)
	},
	{
		deep: true
	}
)
</script>

<style lang="scss" scoped>
.search_view {
	width: 1280px;
	margin: 0 auto;
	.news_show_content {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}
}
</style>
